package net.bmwgroup.easyrule.demo;

import net.bmwgroup.easyrule.demo.facts.FactsInitUtils;
import net.bmwgroup.easyrule.demo.listener.BusinessRuleListener;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.mvel.MVELRuleFactory;
import org.jeasy.rules.support.reader.YamlRuleDefinitionReader;

import java.io.File;
import java.io.FileReader;
import java.util.Objects;
import java.util.function.BiConsumer;

public class EasyRuleDemo {
    public static void main(String[] args) {
        System.out.println("Start execute rules ...");
        // init facts
        Facts facts = FactsInitUtils.initFacts();


//        ParserContext parserContext = new ParserContext();
//        parserContext.addImport(User.class);
//        Serializable test = MVEL.compileExpression("User test = new User();", parserContext);
//        parserContext.addVariable("test", User.class);
//        MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader(), parserContext);


        // create rules from yaml file
        MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
        //load rule from file and register it to the rule engine
        BiConsumer<String, Rules> consumer = (path, rules) -> {
            Rule rule = null;
            try {
                rule = ruleFactory.createRule(new FileReader(path));
            } catch (Exception e) {
                //log
                e.printStackTrace();
            }
            rules.register(rule);
        };

        Rules rules = new Rules();
        //load rules from files
        String path = Objects.requireNonNull(EasyRuleDemo.class.getClassLoader().getResource("")).getPath() + "/rules/";
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < Objects.requireNonNull(tempList).length; i++) {
            if (tempList[i].isFile()) {
                consumer.accept(tempList[i].toString(), rules);
            }
        }

        // create a rules engine
        // fire rules on known facts
        DefaultRulesEngine rulesEngine = new DefaultRulesEngine();
        rulesEngine.registerRuleListener(new BusinessRuleListener());
        long startTime = System.currentTimeMillis();
        rulesEngine.fire(rules, facts);
        System.out.println("Execute rules end... Elapsed time :" + (System.currentTimeMillis() - startTime) + " milliseconds");
        System.exit(0);
    }
}
